﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Collections.ObjectModel;
using System.Data.Objects.DataClasses;
using System.Data.Common;
using System.Data;
using CCF20Model.ModelBase;
using WiseLink.RDS.Resource;

namespace CCF20Model
{
    public class VehicleData
    {
        public Vehicle  MyVehicle { get; set; }
        public Device MyDevice { get; set; }
        public Customer MyCustomer { get; set; }
    }
    
    public class VehicleModel : ModelBase.ModelBaseClass
    {

        public IQueryable<VehicleData> GetRegisteredVehicle()
        {
            //选择所有注册过的车子
            var query= from v in ccf20Entities.Vehicles
                        where v.Devices.FirstOrDefault().IsRegistered == true
                        orderby v.LatestActiveTime descending
                        select new VehicleData
                        {
                            MyVehicle = v,
                            MyCustomer = v.Customer,
                            MyDevice = v.Devices.FirstOrDefault()

                        };
            RefreshQuery(query);
            return query;
            
        }
        
        
        // Get All Vehicles 
        public IQueryable<VehicleData> GetAllVehicles(bool IsActive)
        {
            if (IsActive)
            {
                //只选择目前至少有1种状况的车子
                var queryActive = from v in ccf20Entities.Vehicles
                                   where v.IsActive
                                   orderby v.LatestActiveTime descending
                                   select new VehicleData
                                   {
                                       MyVehicle = v,
                                       MyCustomer = v.Customer,
                                       MyDevice = v.Devices.FirstOrDefault()

                                   };
                
                RefreshQuery(queryActive);
                return queryActive;
            }
            else
            {
                //选择所有的车子，包括没有状况的车辆
                var queryNonActive = from v in ccf20Entities.Vehicles
                                    where v.Devices.Count>0 && v.Devices.FirstOrDefault().IsRegistered == true 
                                    orderby v.LatestActiveTime descending
                                    select new VehicleData
                                    {
                                        MyVehicle = v,
                                        MyCustomer = v.Customer,
                                        MyDevice = v.Devices.FirstOrDefault()

                                    };
                RefreshQuery(queryNonActive);
                return queryNonActive;
            }
        }
        
        public CustomizeTypeCollection<Fault> GetFaultByVehicle(int vehicleID,bool IsActive, string faultType, bool IsConfirmed)
        {
            
            var query = from f in ccf20Entities.Faults
                        where (f.IsActive == IsActive && 
                               f.IsConfirmed ==IsConfirmed &&
                               f.VehicleID == vehicleID &&
                               f.FaultType == faultType)
                        orderby f.HappenDate descending
                        select f;
            RefreshQuery(query);
            return new CustomizeTypeCollection<Fault>(query, this.ccf20Entities);
        }
        //车辆诊断模块，确认过的故障码
        public CustomizeTypeCollection<Fault> GetUnconfirmedFaultByVehicle(int vehicleID)
        {
            return GetFaultByVehicle(vehicleID, true, WiseLinkRDSStatus.Fault_Type_Fault, false);
        }
        
        //客户关怀模块，确认过的故障码
        public CustomizeTypeCollection<Fault> GetConfirmedFaultByVehicle(int vehicleID)
        {
            return GetFaultByVehicle(vehicleID, true, WiseLinkRDSStatus.Fault_Type_Fault, true);
            
        }

        //经理查询模块，所有故障码 包括已处理和未处理的
        public IQueryable<Fault> GetAllFaultByVehicle(int vehicleID)
        {
            var query =    from f in ccf20Entities.Faults
                           where f.VehicleID == vehicleID && f.FaultType.Contains(WiseLinkRDSStatus.Fault_Type_Fault) && f.CloseReason != "重复故障"
                           orderby f.HappenDate descending
                           select f;
            return query;
        }

        //经理查询模块，所有撞车记录 包括已处理和未处理的 IsActive-- True:当前有撞车还未处理    False：无论是否处理，包括已经处理过的历史记录
        public IQueryable<Fault> GetCrashByVehicle(int vehicleID,bool IsActive)
        {
            if (IsActive)
            {
                var queryActive =  from f in ccf20Entities.Faults
                                   where (f.IsActive && f.VehicleID == vehicleID && f.FaultType.Contains(WiseLinkRDSStatus.Fault_Type_Urgent))
                                   orderby f.HappenDate descending
                                   select f;
                RefreshQuery(queryActive);
                return queryActive;
            }
            else
            {
                var queryNonActive =   from f in ccf20Entities.Faults
                                       where (f.VehicleID == vehicleID && f.FaultType.Contains(WiseLinkRDSStatus.Fault_Type_Urgent))
                                       orderby f.HappenDate descending
                                       select f;
                RefreshQuery(queryNonActive);
                return queryNonActive;
            }
        }
        public IQueryable<VehicleRepairHistory> GetRepairHistoryByVehicle(int vehicleID, bool IsActive)
        {
            if (IsActive)
            {
                // 正在维修
                return from f in ccf20Entities.VehicleRepairHistories
                       where (f.IsActive && f.VehicleID == vehicleID)
                       orderby f.InShopDate descending
                       select f;
            }
            else
            {
                //所有过去的维修记录 （包括现在）
                return from f in ccf20Entities.VehicleRepairHistories
                       where f.VehicleID == vehicleID
                       orderby f.InShopDate descending
                       select f;
            }
        }

        public CustomizeTypeCollection<ContactHistory> GetContactHistoryByVehicle(int vehicleID, bool IsActive)
        {
            if (IsActive)
            {
                var query = from c in ccf20Entities.ContactHistories
                               where (c.IsActive && c.VehicleID == vehicleID)
                               orderby c.ContactTime descending
                               select c;

                return new CustomizeTypeCollection<ContactHistory>(query, this.ccf20Entities);
            }
            else
            {
                var query = from c in ccf20Entities.ContactHistories
                               where (c.VehicleID == vehicleID)
                               orderby c.ContactTime descending
                               select c;
                return new CustomizeTypeCollection<ContactHistory>(query, this.ccf20Entities);
            }
            
        }
        public IQueryable<VehicleMaintenanceHistory> GetVehicleMaintenanceRequestByVehicle(int vehicleID,bool IsActive)
        {
            if (IsActive)
            {
                return from v in ccf20Entities.VehicleMaintenanceHistories
                       where (v.IsActive && v.VehicleID == vehicleID)
                       select v;
            }
            else
            {
                return from v in ccf20Entities.VehicleMaintenanceHistories
                       where (v.VehicleID == vehicleID)
                       select v;
            }
        }
        public IQueryable<VehicleMaintenanceRecord> GetVehicleMaintenanceRecordByVehicle(int vehicleID)
        {
            return from v in ccf20Entities.VehicleMaintenanceRecords
                   where v.IsActive && v.VehicleID == vehicleID
                   orderby v.ActiveDate descending
                   select v;
        }
        
        public IQueryable<VehicleMaintenanceHistory> GetVehicleMaintenanceHistoryByVehicle(int vehicleID)
        {
            return from v in ccf20Entities.VehicleMaintenanceHistories
                   where v.VehicleID == vehicleID
                   orderby v.ReceiveDate descending
                   select v;
        }
        public CustomizeTypeCollection<SMSHistory> GetSMSHistoryByVehicle(int vehicleID, bool IsActive)
        {
            if (IsActive)
            {
                var query = from s in ccf20Entities.SMSHistories
                               where (s.IsActive && s.VehicleID == vehicleID)
                               orderby s.QueueTime descending
                               select s;

                return new CustomizeTypeCollection<SMSHistory>(query, this.ccf20Entities);
            }
            else
            {
                var query = from s in ccf20Entities.SMSHistories
                               where s.VehicleID == vehicleID
                               orderby s.QueueTime descending
                               select s;
                return new CustomizeTypeCollection<SMSHistory>(query, this.ccf20Entities);
            }

        }
        public VehicleModel(CCF20Entities ccf20) :base(ccf20)
        {
            
        }
        
        
        private void UpdateFirstContactTime(Vehicle vehicle,VehicleRepairHistory repairHistory)
        {
            foreach (Fault fault in ccf20Entities.Faults.Where(f => f.IsActive && f.VehicleID == vehicle.VehicleID && f.FirstContactDate == null))
            {
                fault.FirstContactDate = DateTime.Now;
                fault.VehicleRepairHistoryID = repairHistory.VehicleRepairHistoryID;
            }
            foreach( VehicleMaintenanceHistory vmh in ccf20Entities.VehicleMaintenanceHistories.Where(m=>m.IsActive && m.VehicleID == vehicle.VehicleID && m.FirstContactDate == null))
            {
                vmh.FirstContactDate = DateTime.Now;
                vmh.VehicleRepairHistoryID = repairHistory.VehicleRepairHistoryID;
            }
        }


        public void AddContactHistoryForVehicle(Vehicle vehicle, string contactResult)
        {
            VehicleRepairHistory repairHistory = VehicleRepairStart(vehicle,null);

            ContactHistory contactHistory = new ContactHistory();
            contactHistory.ContactResult = contactResult;
            contactHistory.IsActive = true;
            contactHistory.ContactTime = DateTime.Now;
            contactHistory.Vehicle = vehicle;
            contactHistory.Operator = vehicle.Operator;
            contactHistory.VehicleRepairHistoryID = repairHistory.VehicleRepairHistoryID;
            ccf20Entities.ContactHistories.AddObject(contactHistory);
            
            UpdateFirstContactTime(vehicle, repairHistory);
            ccf20Entities.SaveChanges();
            if (contactHistory.ContactResult.Contains(WiseLinkRDSStatus.Contact_Reject))
            {
                DeclineCustomer(vehicle, contactHistory.ContactResult);

            }
        }


        public void AddSMSHistoryForVehicle(Vehicle vehicle, SMSHistory sh)
        {
            VehicleRepairHistory repairHistory = VehicleRepairStart(vehicle, null);
            sh.VehicleRepairHistoryID = repairHistory.VehicleRepairHistoryID;
            ccf20Entities.SMSHistories.AddObject(sh);
            UpdateFirstContactTime(vehicle, repairHistory);
            ccf20Entities.SaveChanges();
            
        }

        //客户回场
        public VehicleRepairHistory VehicleRepairStart(Vehicle vehicle,DateTime? inShopDate)
        {
            VehicleRepairHistory repairHistory = ccf20Entities.VehicleRepairHistories.Where(v => v.VehicleID == vehicle.VehicleID && v.IsActive).FirstOrDefault();
            if (repairHistory == null)
            {
                repairHistory = new VehicleRepairHistory();
                repairHistory.VehicleID = vehicle.VehicleID;
                repairHistory.IsActive = true;
                ccf20Entities.VehicleRepairHistories.AddObject(repairHistory);
                
            }
            if (inShopDate != null)
            {
                repairHistory.InShopDate = inShopDate;
            }
            ccf20Entities.SaveChanges();
            return repairHistory;

        }
        //客户出场
        public void VehicleRepairEnd(Vehicle vehicle, int cost, string reason)
        {
            //客户必须先回场，才可以出场
            VehicleRepairHistory repairHistory = ccf20Entities.VehicleRepairHistories.Where(v => v.VehicleID == vehicle.VehicleID && v.IsActive).FirstOrDefault();
            if (repairHistory == null)
            {
                throw new Exception(Message.Care_Cant_OutShop);
            }

            repairHistory.OutShopDate = DateTime.Now;
            repairHistory.RepairCost = cost;
            repairHistory.CloseReason = reason;
            repairHistory.IsActive = false;
            //对于客户出场，我们需要Reset 与车辆相关的状态，
            ResetVehicle(vehicle, reason,repairHistory);
            

        }
        public void HandlePrePriorityMaintenance(int? AnchiID, int? Priority,int serviceMileage,Vehicle vehicle)
        {
            //找到以前的还未结束的同一个保养项目。按理应该先完成以前的保养。但当客户跳过以前的保养次数例如1，2直接做3的出场时。把1，2也一起做了。
            //只有从MAINTENANCETYPE中才可以找到全部 <Currrent Priority 的保养项目。并把它们加入定制，但是不激活.
            var previousVMR = ccf20Entities.MaintenanceTypes.Where( v => v.AnchiID == AnchiID && v.Priority < Priority );

            if (previousVMR.Count()  == 0)
            {
                LoggerHelper.LogCCF20(string.Format("[客户实际出场]保养AnchiID={0}不存在次数小于 当前次数={1}的保养", AnchiID, Priority));
            }
            else
            {
                LoggerHelper.LogCCF20(string.Format("[客户实际出场]保养AnchiID={0}存在次数小于 当前次数={1}的保养,共有{2}条保养，需要确定取消", AnchiID, Priority, previousVMR.Count()));


                foreach (MaintenanceType pvmr in previousVMR)
                {
                    VehicleMaintenanceRecord currentVMR = ccf20Entities.VehicleMaintenanceRecords.Where(
                                                                               v => v.VehicleID == vehicle.VehicleID && 
                                                                                    v.AnchiID == pvmr.AnchiID &&
                                                                                    v.Priority == pvmr.Priority)
                                                                                    .FirstOrDefault();
                    if (currentVMR == null)
                    {

                        currentVMR = new VehicleMaintenanceRecord();
                        currentVMR.MaintenanceTypeID = pvmr.MaintenanceTypeID;
                        currentVMR.Priority = pvmr.Priority;
                        currentVMR.ServiceMileage = pvmr.ServiceMileage;
                        currentVMR.ServicePeriod = pvmr.ServicePeriod;

                        currentVMR.VehicleID = vehicle.VehicleID;
                        currentVMR.AnchiID = pvmr.AnchiID;
                        ccf20Entities.VehicleMaintenanceRecords.AddObject(currentVMR);

                        LoggerHelper.LogCCF20(string.Format("[客户实际出场]上一次保养={0} 次数={1} 激活={2}不在VMR里，向VMR插入一条新记录",
                                                currentVMR.MaintenanceType.Name,
                                                currentVMR.MaintenanceType.Priority,
                                                currentVMR.IsActive));

                    }
                    else
                    {
                        LoggerHelper.LogCCF20(string.Format("[客户实际出场]上一次保养={0} 次数={1} 激活={2}已经在VMR里",
                                              currentVMR.MaintenanceType.Name,
                                              currentVMR.MaintenanceType.Priority,
                                              currentVMR.IsActive));

                    }

                    currentVMR.IsActive = false;
                    currentVMR.LastServiceMileage = serviceMileage;
                    currentVMR.LastServiceDate = DateTime.Now;

                }
            }
        }
        public void HandleCurrentPriorityMaintenance(int? AnchiID, int? Priority, int serviceMileage, Vehicle vehicle, bool isActive)
        {
            VehicleMaintenanceRecord currentVMR = ccf20Entities.VehicleMaintenanceRecords.Where(v => v.AnchiID == AnchiID && 
                                                                                                     v.Priority == Priority &&
                                                                                                     v.VehicleID == vehicle.VehicleID &&
                                                                                                     v.IsActive == true)
                                                                                         .FirstOrDefault();


            //如果Current 保养已经在VMR里，则不处理。否则，向VMR插入一条新记录
            if (currentVMR == null)
            {
                currentVMR = new VehicleMaintenanceRecord();
                ccf20Entities.VehicleMaintenanceRecords.AddObject(currentVMR);
                MaintenanceType currentMaintenanceType = ccf20Entities.MaintenanceTypes.Where(v => v.AnchiID == AnchiID && v.Priority == Priority).FirstOrDefault();
                currentVMR.MaintenanceTypeID = currentMaintenanceType.MaintenanceTypeID;
                currentVMR.Priority = currentMaintenanceType.Priority;
                currentVMR.ServiceMileage = currentMaintenanceType.ServiceMileage;
                currentVMR.ServicePeriod = currentMaintenanceType.ServicePeriod;
                currentVMR.VehicleID = vehicle.VehicleID;
                currentVMR.AnchiID = currentMaintenanceType.AnchiID;

                LoggerHelper.LogCCF20(string.Format("[客户实际出场]当前保养={0} 次数={1} 激活={2}不在VMR里，向VMR插入一条新记录",
                                        currentVMR.MaintenanceType.Name,
                                        currentVMR.MaintenanceType.Priority,
                                        currentVMR.IsActive));

            }
            else
            {
                LoggerHelper.LogCCF20(string.Format("[客户实际出场]当前保养={0} 次数={1} 激活={2}已经在VMR里",
                                        currentVMR.MaintenanceType.Name,
                                        currentVMR.MaintenanceType.Priority,
                                        currentVMR.IsActive));

            }
            currentVMR.LastServiceMileage = serviceMileage;
            currentVMR.LastServiceDate = DateTime.Now;
            currentVMR.IsActive = isActive;
        }
        public void HandleNextPriorityMaintenance(int? AnchiID, int? Priority, int serviceMileage, Vehicle vehicle)
        {
            MaintenanceType nextMaintenanceType = ccf20Entities.MaintenanceTypes.Where(v => v.AnchiID == AnchiID && 
                                                                                            v.Priority > Priority)
                                                                                        .OrderBy( v=>v.Priority )
                                                                                        .FirstOrDefault();
            if (nextMaintenanceType != null)
            {
                LoggerHelper.LogCCF20(string.Format("[客户实际出场] 保养={0}项目里存在下一次={1}记录", nextMaintenanceType.Name, nextMaintenanceType.Priority));
                VehicleMaintenanceRecord nextVMR = ccf20Entities.VehicleMaintenanceRecords.Where(v => v.VehicleID == vehicle.VehicleID &&
                                                                                                      v.AnchiID == nextMaintenanceType.AnchiID &&
                                                                                                      v.Priority == nextMaintenanceType.Priority)
                                                                                           .FirstOrDefault();
                                                                                           

                //如果NEXT 保养已经在VMR里，则确认他处于激活状态。否则，向VMR插入一条新记录
                if (nextVMR == null)
                {
                    nextVMR = new VehicleMaintenanceRecord();
                    nextVMR.MaintenanceTypeID = nextMaintenanceType.MaintenanceTypeID;
                    nextVMR.Priority = nextMaintenanceType.Priority;
                    nextVMR.ServiceMileage = nextMaintenanceType.ServiceMileage;
                    nextVMR.ServicePeriod = nextMaintenanceType.ServicePeriod;
                    nextVMR.VehicleID = vehicle.VehicleID;
                    nextVMR.AnchiID = nextMaintenanceType.AnchiID;
                    ccf20Entities.VehicleMaintenanceRecords.AddObject(nextVMR);
                    LoggerHelper.LogCCF20(string.Format("[客户实际出场]下一次保养={0} 次数={1} 激活={2}不在VMR里，向VMR插入一条新记录",
                                            nextVMR.MaintenanceType.Name,
                                            nextVMR.MaintenanceType.Priority,
                                            nextVMR.IsActive));
                }
                else
                {
                    LoggerHelper.LogCCF20(string.Format("[客户实际出场]下一次保养={0} 次数={1} 激活={2} 已经在VMR里",
                                            nextVMR.MaintenanceType.Name,
                                            nextVMR.MaintenanceType.Priority,
                                            nextVMR.IsActive));
                }
                
                nextVMR.LastServiceMileage = serviceMileage;
                nextVMR.LastServiceDate = DateTime.Now;
                nextVMR.IsActive = true;
                
                //如果有NEXT保养，则要看当前保养是否已经在VMR里，在不处理。否则，向VMR插入一条新记录
                // 但不管怎样，都不激活它
                LoggerHelper.LogCCF20(string.Format("[客户实际出场]激活下一次保养={0} 次数={1} 取消当前次数={2}的保养", 
                                            nextVMR.MaintenanceType.Name,
                                            nextVMR.MaintenanceType.Priority,
                                            Priority));
                HandleCurrentPriorityMaintenance(AnchiID, Priority, serviceMileage, vehicle, false);
            }
            else
            {
                //如果没有NEXT保养，则要看当前保养是否已经在VMR里，在不处理。否则，向VMR插入一条新记录
                // 但不管怎样，都激活它
                LoggerHelper.LogCCF20(string.Format("[客户实际出场]当前保养AnchiID={0}无下一次保养记录，保持当前次数={1}的保养", AnchiID, Priority));
                HandleCurrentPriorityMaintenance(AnchiID, Priority, serviceMileage, vehicle, true);
                
            }

        }
        public void AddVehicleMaintenanceHistory(Vehicle vehicle, CombinedMaintenanceType combinedMaintenance,int serviceMileage)
        {
            VehicleRepairHistory repairHistory = VehicleRepairStart(vehicle,null);
            
                //如果在出场时，用户选择了没有定制的其他保养项目，就把它自动加入定制保养里
                //如果该保养项目有下一个次数的保养，则把下一个保养 （激活）自动加入定制保养里,
                //无论如何都把当前保养记录自动加入定制保养，因为我们确实做了该项的保养。但如果没有下一个次数的保养则当前保养为活动保养，如果有下一个次数的保养则为非激活保养。
                //所以当我们在客户实际出场时取ZXT保养和定制保养是可以免去已经完成的保养
                //对于保养历史记录，用当前的保养记录
                HandleNextPriorityMaintenance(combinedMaintenance.MaintenanceType.AnchiID,
                                             combinedMaintenance.MaintenanceType.Priority,
                                             serviceMileage,
                                             vehicle);
                
                    //找到下一次的同一个保养项目
                HandlePrePriorityMaintenance(combinedMaintenance.MaintenanceType.AnchiID,
                                             combinedMaintenance.MaintenanceType.Priority,
                                             serviceMileage,
                                             vehicle);
                
                VehicleMaintenanceRecord currentVMR = new VehicleMaintenanceRecord();

                currentVMR.MaintenanceTypeID = combinedMaintenance.MaintenanceType.MaintenanceTypeID;
                currentVMR.Priority = combinedMaintenance.MaintenanceType.Priority;
                currentVMR.ServiceMileage = combinedMaintenance.MaintenanceType.ServiceMileage;
                currentVMR.ServicePeriod = combinedMaintenance.MaintenanceType.ServicePeriod;
                currentVMR.LastServiceMileage = serviceMileage;
                currentVMR.LastServiceDate = DateTime.Now;
                currentVMR.VehicleID = vehicle.VehicleID;
                currentVMR.AnchiID = combinedMaintenance.MaintenanceType.AnchiID;
                currentVMR.IsActive = true;
                
                AddVehicleMaintenanceHistory(vehicle, currentVMR, repairHistory.VehicleRepairHistoryID, serviceMileage);
            
        }
        private void AddVehicleMaintenanceHistory(Vehicle vehicle, VehicleMaintenanceRecord vehicleMaintenanceRecord, int repairHistoryID, int serviceMileage)
        {
            VehicleMaintenanceHistory vmh = ccf20Entities.VehicleMaintenanceHistories.Where(
                                                v => v.IsActive &&
                                                    v.VehicleID == vehicle.VehicleID &&
                                                    v.MaintenanceTypeID == vehicleMaintenanceRecord.MaintenanceTypeID)
                                                    .FirstOrDefault();
            if (vmh == null)
            {
                vmh = new VehicleMaintenanceHistory();
                ccf20Entities.VehicleMaintenanceHistories.AddObject(vmh);
                vmh.MaintenanceTypeID = vehicleMaintenanceRecord.MaintenanceTypeID;
                vmh.HappenDate = DateTime.Now;
                vmh.ReceiveDate = DateTime.Now;
                vmh.LastServiceDate = vehicle.LastServcieDate;
                vmh.LastServiceMileage = vehicle.LastServiceMileage;
                vmh.EffectiveReceiveDate = DateTime.Now;
                vmh.CareScore = 0;
                vmh.Priority = vehicleMaintenanceRecord.Priority;
                
            }
            vmh.VehicleID = vehicle.VehicleID;
            vmh.DeviceID = vehicle.Devices.First().DeviceID;
            vmh.FirstContactDate = vmh.FirstContactDate ?? DateTime.Now;
            vmh.VehicleRepairHistoryID = repairHistoryID;
            vmh.CurrentMileage = serviceMileage;
            vmh.CloseDate = DateTime.Now;
            vmh.CloseReason = "客户出场";
            vmh.IsActive = false;
            
            ccf20Entities.SaveChanges();

        }
        public void DeclineCustomer(Vehicle vehicle,string reason)
        {
            //对于拒绝或放弃的客户，模拟回场与出场
            VehicleRepairHistory vrh= VehicleRepairStart(vehicle,null);
            //对于对于拒绝或放弃的客户，我们需要Reset 与车辆相关的状态，
            //同时虚拟保养项目的处理, X新需求，客户拒绝是不出场，保持现在状态，里程
            //HandleMaintenanceRecord(vehicle, reason);
            //ResetVehicle(vehicle, reason);
            VehicleRepairEnd(vehicle, 0, reason);
        }
        public void RestoreCustomer(Vehicle vehicle)
        {
            vehicle.LastContactResult = WiseLinkRDSStatus.Contact_NotContactYet;
            vehicle.PreviousContactResult = string.Empty;
            ccf20Entities.SaveChanges();
            AddContactHistoryForVehicle(vehicle, WiseLinkRDSStatus.Contact_Restore);

        }
        public void GiveUpCustomer(Vehicle vehicle)
        {
            
            //对于拒绝或放弃的客户，模拟回场与出场
            VehicleRepairStart(vehicle,null);
            ccf20Entities.SaveChanges();
            AddContactHistoryForVehicle(vehicle, WiseLinkRDSStatus.Contact_Giveup);

            VehicleRepairEnd(vehicle, 0, WiseLinkRDSStatus.Contact_Giveup);
        }
        public void RemoveUrgent(Vehicle vehicle)
        {
            foreach (Fault fault in vehicle.Faults.Where(f => f.FaultType.Contains(WiseLinkRDSStatus.Fault_Type_Urgent) && f.IsActive))
            {
                fault.IsActive = false;
                fault.FirstContactDate = DateTime.Now;
                fault.CloseDate = DateTime.Now;
                fault.CloseReason = "排除急救";
            }
            
            foreach (UrgentSMSQueue urgentSMS in vehicle.UrgentSMSQueues.Where(c => c.IsActive))
            {
                urgentSMS.IsActive = false;
                urgentSMS.CloseReason = "排除急救";
                urgentSMS.Operator = vehicle.Operator;
                urgentSMS.CloseDate = DateTime.Now;
            }
            
            vehicle.LastContactResult = vehicle.PreviousContactResult;
            ccf20Entities.SaveChanges();
        }
        //public void HandleMaintenanceRecord(Vehicle vehicle, string reason)
        //{
        //    VehicleRepairHistory vrh = VehicleRepairStart(vehicle);
        //    foreach (VehicleMaintenanceRecord vmr in vehicle.VehicleMaintenanceRecords)
        //    {
        //        AddVehicleMaintenanceHistory(vehicle, vmr.MaintenanceType,vrh,reason);
        //    }
        //    ccf20Entities.SaveChanges();
        //}
        public void ResetVehicle(Vehicle vehicle,string reason, VehicleRepairHistory vrh)
        {
            
            // reset vehicle table vehiclestatus
            vehicle.IsActive = false;
            vehicle.IsFault = false;
            vehicle.IsMaintenance = false;
            vehicle.IsUrgent = false;
            vehicle.LastContactResult = reason;
            vehicle.LastContactTime = DateTime.Now;
            //vehicle.LatestActiveTime = DateTime.Now;
            vehicle.BookTime = null;
            vehicle.PreviousContactResult = string.Empty;
            

            // clear faults table
            // clear VehicleMaintenanceHistoryTable
            // clear smshistory
            // clear contacthistory
            // Reset vehicleMaintenanceRecord (LastServiceMileage, LastServiceDate)
            //    *** we shouldn't reset vehicleMaintenanceRecord when 客户出场
            //    *** 客户出场时，我们基于客户所选取的保养项目进行维护项目的重置。


            foreach (UrgentSMSQueue urgentSMS in vehicle.UrgentSMSQueues.Where(c => c.IsActive))
            {
                urgentSMS.IsActive = false;
                urgentSMS.VehicleRepairHistoryID = vrh.VehicleRepairHistoryID;
                urgentSMS.CloseReason = reason;
                urgentSMS.Operator = vehicle.Operator;
                urgentSMS.CloseDate = DateTime.Now;
            }
            foreach (ContactHistory ch in vehicle.ContactHistories.Where(c => c.IsActive))
            {
                ch.IsActive = false;
                ch.CloseDate = DateTime.Now;
                ch.VehicleRepairHistoryID = vrh.VehicleRepairHistoryID;
                ch.CloseReason = reason;
                ch.Operator = vehicle.Operator;
            }
            foreach (SMSHistory ch in vehicle.SMSHistories.Where(c => c.IsActive))
            {
                ch.IsActive = false;
                ch.CloseDate = DateTime.Now;
                ch.VehicleRepairHistoryID = vrh.VehicleRepairHistoryID;
                ch.CloseReason = reason;
                ch.Operator = vehicle.Operator;
            }
            foreach (Fault ch in vehicle.Faults.Where(c => c.IsActive))
            {
                ch.IsActive = false;
                ch.CloseDate = DateTime.Now;
                if (ch.FirstContactDate == null) ch.FirstContactDate = DateTime.Now;
                ch.VehicleRepairHistoryID = vrh.VehicleRepairHistoryID;
                ch.CloseReason = reason;
                ch.Operator = vehicle.Operator;
            }
            foreach (VehicleMaintenanceHistory ch in vehicle.VehicleMaintenanceHistories.Where(c => c.IsActive))
            {
                ch.IsActive = false;
                ch.CloseDate = DateTime.Now;
                ch.CloseReason = reason;
                ch.VehicleRepairHistoryID = vrh.VehicleRepairHistoryID;
                ch.CurrentMileage = vehicle.CurrentMileage;
                ch.Operator = vehicle.Operator;
                if (ch.FirstContactDate == null) ch.FirstContactDate = DateTime.Now;

            }
            if (!reason.Contains(WiseLinkRDSStatus.Contact_OutShop))
            {
                foreach (VehicleMaintenanceRecord vmr in vehicle.VehicleMaintenanceRecords)
                {
                    vmr.LastServiceDate = DateTime.Now;
                    vmr.LastServiceMileage = vehicle.CurrentMileage;
                    vmr.Operator = vehicle.Operator;
                }
            }
            ccf20Entities.SaveChanges();
        }
        public void ExecuteSql(CCF20Entities c, string sql) 
        {
            if (c == null) c = this.ccf20Entities;
            var entityConnection = (System.Data.EntityClient.EntityConnection)c.Connection;
            DbConnection conn = entityConnection.StoreConnection;      
            ConnectionState initialState = conn.State;     
            try     
            { 
                if (initialState != ConnectionState.Open)        
                    conn.Open();  // open connection if not already open          
                using (DbCommand cmd = conn.CreateCommand())       
                {              
                    cmd.CommandText = sql;        
                    cmd.ExecuteNonQuery();          
                }
            }
            finally 
            { 
                if (initialState != ConnectionState.Open)   
                    conn.Close(); // only close connection if not initially open  
            }
        }
        public object GetZICLastResponseID(ZICResponseCategory zicResposneCategory)
        {
            CCF20Entities ccf20Entities = new CCF20Entities();
            using (ccf20Entities)
            {
                ZICResponse zicResponse;
                switch (zicResposneCategory)
                {
                    case ZICResponseCategory.GetDeviceStatus:
                        zicResponse = ccf20Entities.ZICResponses.Where(z => z.ResponseCategory.Equals("GetDeviceStatus")).FirstOrDefault();
                        if (zicResponse != null)
                        {
                            return zicResponse.ResponseTime;
                        }
                        else
                        {
                            return new DateTime(2011, 1, 1);
                        }

                }
                return null;
            }

        }
        public bool UpdateDeviceUsageStatus(string idc, string status)
        {
            Device device = ccf20Entities.Devices.Where(d => d.IDCSimNumber.Trim() == idc.Trim()).FirstOrDefault();
            if (device == null)
            {
                LoggerHelper.LogZICDebug(string.Format("[设备使用状态] Can't find IDC={0}", idc));
                return false;
            }
            else
            {
                LoggerHelper.LogZICDebug(string.Format("[设备使用状态] Update IDC={0} DeviceUsageStatus = {1}", idc, status));
                device.UsageStatus = status;
                ccf20Entities.SaveChanges();
                return true;
            }
        }
        public void UpdateZICLastResponseID(ZICResponseCategory zicResposneCategory)
        {
            ZICResponse zicResponse;
            switch (zicResposneCategory)
            {
                case ZICResponseCategory.GetDeviceStatus:
                    zicResponse = ccf20Entities.ZICResponses.Where(z => z.ResponseCategory.Equals("GetDeviceStatus")).FirstOrDefault();
                    if (zicResponse == null)
                    {
                        zicResponse = new ZICResponse();
                        ccf20Entities.ZICResponses.AddObject(zicResponse);
                        zicResponse.ResponseCategory = "GetDeviceStatus";
                    }
                    zicResponse.ResponseTime = DateTime.Now;
                    ccf20Entities.SaveChanges();
                    break;
            }

        }
        public int GetMaxClearCodeResultId()
        {
            return ccf20Entities.ClearCodeHistories.Max(c => c.AnchiID) ?? 0;
        }
        public void AddClearCodeResult(ClearCodeHistory cch)
        {
            ccf20Entities.ClearCodeHistories.AddObject(cch);
            ccf20Entities.SaveChanges();
        }


        public IEnumerable<ClearCodeHistory> GetClearCodeResultByVehicle(string idc)
        {
            return ccf20Entities.ClearCodeHistories.Where(c => c.IDCSimNumber == idc);
        }

        public void AddDefectedProduct(string idc)
        {
            if (ccf20Entities.Devices.Count(d => d.IDCSimNumber == idc) == 1 &&
                 ccf20Entities.Devices.Count(d => d.IDCSimNumber == idc && d.IsDefected == true) == 0 &&
                 ccf20Entities.TroubledDevices.Count(t => t.Device.IDCSimNumber == idc) == 0)
            {
                //该IDC属于这个IDS
                //我们还未确认该IDC是损坏的
                //我们还未知道该IDC是损坏的
                TroubledDevice td = new TroubledDevice();
                td.DeviceID = ccf20Entities.Devices.Where(d => d.IDCSimNumber == idc).FirstOrDefault().DeviceID;
                ccf20Entities.TroubledDevices.AddObject(td);
                ccf20Entities.SaveChanges();
                LoggerHelper.LogZICDebug(string.Format("Add DefectedProduct IDC={0}", idc));
            }
            else
            {
                LoggerHelper.LogZICDebug(string.Format("收到 DefectedProduct IDC={0} 但是没有写入数据库", idc));
            }
        }

        
    }
}
